package com.kite.ossServer;

import android.webkit.JavascriptInterface;
import java.io.*;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;

public class FileAble {

    // ============ 文件写入操作 ============

    /**
     * 写入文本到文件 - 重构版本，返回JSON响应而不是抛出异常
     */
    @JavascriptInterface
    public static String writeTextToFile(String filePath, String text) {
        try {
            if (filePath == null || filePath.trim().isEmpty()) {
                return createErrorResponse("文件路径不能为空");
            }

            if (text == null) {
                text = "";
            }

            File file = new File(filePath);

            // 确保父目录存在
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                if (!parentDir.mkdirs()) {
                    return createErrorResponse("无法创建父目录: " + parentDir.getAbsolutePath());
                }
            }

            try (BufferedWriter bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
                bufferedWriter.write(text);
                bufferedWriter.flush();
                return createSuccessResponse("写入成功");
            }
        } catch (SecurityException e) {
            return createErrorResponse("写入失败，没有足够权限: " + e.getMessage());
        } catch (Exception e) {
            return createErrorResponse("写入文件失败: " + e.getMessage());
        }
    }

    /**
     * 兼容旧接口的方法
     */
    public static boolean writeText(File file, String text) {
        try {
            String result = writeTextToFile(file.getAbsolutePath(), text);
            JSONObject response = new JSONObject(result);
            return response.getBoolean("success");
        } catch (Exception e) {
            return false;
        }
    }

    // ============ 文件读取操作 ============

    /**
     * 从文件读取文本 - 重构版本，返回JSON响应而不是抛出异常
     */
    @JavascriptInterface
    public static String readTextFromFile(String filePath) {
        try {
            if (filePath == null || filePath.trim().isEmpty()) {
                return createErrorResponse("文件路径不能为空");
            }

            File file = new File(filePath);

            if (!file.exists()) {
                return createErrorResponse("文件不存在: " + filePath);
            }

            if (!file.canRead()) {
                return createErrorResponse("无法读取文件: " + filePath);
            }

            StringBuilder text = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
                char[] buffer = new char[8192];
                int charsRead;
                while ((charsRead = bufferedReader.read(buffer)) != -1) {
                    text.append(buffer, 0, charsRead);
                }
            }

            return createSuccessResponse(text.toString());
        } catch (SecurityException e) {
            return createErrorResponse("读取失败，没有足够权限: " + e.getMessage());
        } catch (Exception e) {
            return createErrorResponse("读取文件失败: " + e.getMessage());
        }
    }

    /**
     * 兼容旧接口的方法
     */
    public static String readText(File file) {
        try {
            String result = readTextFromFile(file.getAbsolutePath());
            JSONObject response = new JSONObject(result);
            return response.getBoolean("success") ? response.getString("data") : "";
        } catch (Exception e) {
            return "";
        }
    }

    // ============ 文件创建操作 ============

    /**
     * 创建文件 - 重构版本，返回JSON响应而不是抛出异常
     */
    @JavascriptInterface
    public static String createFile(String directory, String fileName, String suffix) {
        try {
            if (fileName == null || fileName.trim().isEmpty()) {
                return createErrorResponse("文件名不能为空");
            }

            if (suffix == null || suffix.isEmpty()) {
                suffix = ".json";
            }

            // 确定目标目录
            File targetDir;
            if (directory == null || directory.trim().isEmpty() || "/".equals(directory)) {
                targetDir = new File("/");
            } else {
                targetDir = new File(directory);
            }

            if (!targetDir.exists() && !targetDir.mkdirs()) {
                return createErrorResponse("无法创建目录: " + targetDir.getAbsolutePath());
            }

            File file = new File(targetDir, fileName + suffix);

            // 如果文件已存在，返回成功
            if (file.exists()) {
                return createSuccessResponse(file.getAbsolutePath());
            }

            // 创建文件
            if (file.createNewFile()) {
                return createSuccessResponse(file.getAbsolutePath());
            } else {
                return createErrorResponse("文件创建失败: " + file.getAbsolutePath());
            }
        } catch (SecurityException e) {
            return createErrorResponse("创建失败，没有足够权限: " + e.getMessage());
        } catch (Exception e) {
            return createErrorResponse("创建文件失败: " + e.getMessage());
        }
    }

    /**
     * 兼容旧接口的方法
     */
    public static File createF(String name, String path, String suffix) throws Exception {
        String result = createFile(path, name, suffix);
        JSONObject response = new JSONObject(result);

        if (response.getBoolean("success")) {
            return new File(response.getString("data"));
        } else {
            throw new Exception(response.getString("error"));
        }
    }

    // ============ 辅助方法 ============

    private static String createSuccessResponse(String data) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("data", data);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":true,\"data\":\"" + escapeJson(data) + "\"}";
        }
    }

    private static String createErrorResponse(String error) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", error);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":false,\"error\":\"" + escapeJson(error) + "\"}";
        }
    }

    private static String escapeJson(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
                   .replace("\"", "\\\"")
                   .replace("\b", "\\b")
                   .replace("\f", "\\f")
                   .replace("\n", "\\n")
                   .replace("\r", "\\r")
                   .replace("\t", "\\t");
    }
}
